package controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import models.BaseEntity.Status;
import models.Message;
import models.Message.MessageStatus;
import models.Message.MessageType;
import models.QueryBean;
import play.data.validation.Valid;
import play.mvc.Controller;


public class MessageBoard extends Controller {
	public static void index(QueryBean queryBean, Message editMsg) {
		if(queryBean == null) {
			queryBean = new QueryBean();
		}
		String hql = "id != null and status != ? and type = ? and messageStatus = ? order by createAt, lastModifiedAt desc";
		List<Object> objs = new ArrayList<Object>();
		objs.add(Status.DISABLED);
		objs.add(MessageType.QUESTION);
		objs.add(MessageStatus.PASS);
		
		//页数计算
		queryBean.totalQuantity = Message.count(hql, objs.toArray());
		queryBean.pageCaculate();
		
		List<Message> msgs = Message.find(hql, objs.toArray()).fetch(
				(int)queryBean.currentPage, queryBean.quantityEachPage);
		
		if(editMsg != null) {
			render(editMsg, msgs,queryBean);
		} else {
			render(msgs,queryBean);
		}
	}
    
    /**
	 * 提交留言
	 * 
	 * @param user
	 */
	public static void commitMessage(@Valid Message message){
		//验证必填项
		validation.required("message.title", message.title);
		validation.required("message.content", message.content);
		validation.required("message.author", message.author);
		
		//验证输入最少长度
		validation.minSize("message.title", message.title, 6);
		validation.minSize("message.author", message.author, 2);
		validation.minSize("message.content", message.content, 6);
		
		//验证输入最大长度
		validation.maxSize("message.title", message.title, 20);
		validation.maxSize("message.author", message.author, 20);
		validation.maxSize("message.content", message.content, 200);
		
		if(validation.hasErrors()) {
			params.flash(); // add http parameters to the flash scope
			validation.keep(); // keep the errors for the next request
			index(null, message); 
		} else {
			//设置留言时间
			message.createAt = new Date();
			
			//留言状态设为NEW，待管理员评审通过才能设置为PASS
			message.messageStatus = MessageStatus.NEW;
			
			//设置留言类型
			message.type = MessageType.QUESTION;
			
			message.createAt = new Date();
			message.lastModifiedAt = new Date();
			
			//保存留言信息
			message.save();
			validation.addError("SUCCESS", "SUCCESS");
			validation.keep(); // keep the errors for the next request
			index(null, null); 
		}
		
	}

}